'use strict';

clientApp.controller('MainCtrl', function($scope, $location, model) {

  var User = model.User;

  function start() {

    User.get('me', userHandler, userFailHandler);

  }

  function userHandler(user) {

    console.log('logged in');

    $scope.user = user;

    //store for use in other controllers
    model.user = $scope.user;

  }

  function userFailHandler(e) {

    console.log('not logged in');

    $scope.loginURL = User.login_popup_url(
      function() {

        var loginElement = document.querySelector('.login');
        loginElement.querySelector('form').style.display = 'block';

        var linkElement = loginElement.querySelector('a');
        loginElement.removeChild(linkElement);
        start();

    });

    var loginElement = document.querySelector('.login');
    loginElement.querySelector('form').style.display = 'none';

    var linkElement = document.createElement('a');
    linkElement.innerHTML = 'Login';
    linkElement.href = $scope.loginURL;
    linkElement.target = '_blank';
    loginElement.appendChild(linkElement);

  }

  $scope.saveUsername = function() {

    $scope.user.timestamp = Date.now();
    $scope.user.$save();

    document.querySelector('.login form input').blur();

  };

  start();

});
